package com.gameone.test.tree.data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class DB {
	String table = "role";
	int type = 4;
	int maxDepth = 4;
	int amount = 10;
	int minAmount = 1000;
	List<String> names = new ArrayList<String>();
	List<Integer> parent = new ArrayList<Integer>();

	int depth = 0;

	@Test
	public void genRecords() throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");

		PreparedStatement stmnt = conn.prepareStatement("insert " + table + "(name) values(?)");
		PreparedStatement treeStmnt = conn.prepareStatement("insert tree(id, parent, type) values(?, ?, ?)");

		printChild(0);

		System.out.println(names.size());

		if (names.size() >= minAmount && names.size() <= minAmount * 1.5) {
			for (int i = 0; i < names.size(); i++) {
				stmnt.setString(1, names.get(i));
				stmnt.executeUpdate();

				treeStmnt.setInt(1, i + 1);
				treeStmnt.setInt(2, parent.get(i));
				treeStmnt.setInt(3, type);
				treeStmnt.execute();
			}
		}

		stmnt.close();
		treeStmnt.close();
		conn.close();
	}

	private void printChild(int parentId) throws SQLException {
		depth++;

		if (depth <= maxDepth) {
			// 每层个数
			int count = (int) (Math.random() * (amount + 1));
			for (int i = 1; i <= count; i++) {
				String newName;
				if (parentId == 0) {
					newName = table + i;
				} else {
					newName = names.get(parentId - 1) + i;
				}
				names.add(newName);
				parent.add(parentId);

				printChild(names.size());
			}
		}

		depth--;
	}

	public static void main(String[] args) {
	}
}
